package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * SDH专线-全程要求完成时间
 **/
@Service
public class LocalZxAllCompleteTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);

        String serviceOfferId = Optional.ofNullable(kiteSceneInst).map(KiteSceneInst::getServiceOfferId).orElse("");
        if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER)) {
            String custId = KiteWebContext.getContext().getCust().getCustId();
            KiteInst kiteInst = querySceneInstService.getKiteInst(custId, kiteSceneInst.getRootInstType(), kiteSceneInst.getRootInstId());

            List<DcPublic> list = DcPublicCache.get("20210719001");
            // 是否五大双线落地方产品
            boolean flag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
            if(flag) {
                // 五大双线落地产品默认为空
                return;
            }
        }

        if(KiteStringUtils.equalsAny(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER, "1024",
            LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK, ServiceOfferConsts.SERVICE_OFFER_MODIFY)){
            if(KiteStringUtils.isEmpty(commonAttr.getValue())){
                Date initDate = DateUtil.addDays(new Date(), 5);
                String value = DateUtils.getDateTimeString(initDate,"yyyy-MM-dd");
                commonAttr.setValue(value + " 23:59:59");
                commonAttr.setValueDesc(value);
                setCommonAttr(commonAttr);
            }
        }
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if (KiteStringUtils.isNotEmpty(value) && value.length() == 10){
            value += " 23:59:59";
            valueDesc = value;
        }

        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        List<DcPublic> dclist = DcPublicCache.get("20210719001");
        // 是否五大双线落地方产品，全程要求完成时间一直必填
        boolean flag = (dclist != null) && dclist.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
        if (!flag) {
            //获取页面勾选的操作类型
            List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
            IOperateSceneCommonService operateSceneCommonService = SpringUtil.getBean(IOperateSceneCommonService.class);
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId,LocalKeyConsts.WHOLE_PROCESS_TIME);
            if(Objects.nonNull(kiteAttr)){
                if(!KiteListUtils.isEmpty(serviceOfferIdList)&&serviceOfferIdList.size()==1){
                    if(serviceOfferIdList.contains("1009")||serviceOfferIdList.contains("1080")){
                        kiteAttr.setIsNull("T");
                    }
                    else{
                        kiteAttr.setIsNull("F");
                    }
                }else {
                    kiteAttr.setIsNull("F");
                }
                operateSceneCommonService.setCommonAttr(sceneInstId,kiteAttr);
            }
        }

        // 变更业务的场景初始化过程中不校验
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(sceneInst.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(sceneInstId, LocalKeyConsts.BUSI_CHANGE_SCENE))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(sceneInstId, "initSource"))) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }

        if (KiteStringUtils.isEmpty(value)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        //重提初始化不校验
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams) && extParams.containsKey("nodeCode")) {
            return  super.apply(sceneInstId, fieldName, value, valueDesc);
        }

        String allCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        String azCompleteTimePattern = "yyyy-MM-dd";
        Date curDate = getCurrentDate();


        Date allCompleteTime = null;
        if (KiteStringUtils.isNotEmpty(value)){
            if(allCompleteTimePattern.length() > value.length()) {
                allCompleteTimePattern = allCompleteTimePattern.substring(0, value.length());
            }
            try{
                allCompleteTime = DateUtils.parseStrToDate(value, allCompleteTimePattern);
            }catch (Exception e){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }


            String scenInstId = KiteStringUtils.isEmpty(ContextUtil.getHttpSessoinId()) ? sceneInstId
                : KiteWebContext.getContext().getCurrentSceneInstId();
            List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(scenInstId);
            for(KiteProdInst kiteProdInst : prodInstList){
                //A端要求完成时间
                String aCompleteTimeStr = kiteProdInst.getAttrValue("2_0000122");
                String zCompleteTimeStr = kiteProdInst.getAttrValue("2_0000123");
                List<String> list = new ArrayList<>();
                list.add(aCompleteTimeStr);
                list.add(zCompleteTimeStr);
                for(String complteTimeStr : list){
                    if(KiteStringUtils.isNotEmpty(complteTimeStr)){
                        if(azCompleteTimePattern.length() > complteTimeStr.length()) {
                            azCompleteTimePattern = azCompleteTimePattern.substring(0, complteTimeStr.length());
                        }

                        Date completeDate = null;
                        try{
                            completeDate = DateUtils.parseStrToDate(complteTimeStr,azCompleteTimePattern);
                        }catch(Exception e){
                            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                        }

                        //AZ端完成时间需要小于全局完成当前时间
                        if(null != completeDate && DateUtil.compare(completeDate,allCompleteTime) >1){
                            String nodeCode = querySceneInstService.getExtParameterValue(scenInstId, "nodeCode");
                            // 是否为页面初始化渲染，是（T），跳过校验
                            String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
                            if(KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
                                return super.apply(sceneInstId, fieldName, value, value);
                            } if (KiteStringUtils.equalsAny(nodeCode,"OrderSigned")) {
                                // 签订环节不做校验
                                return super.apply(sceneInstId, fieldName, value, value);
                            } else {
                                BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
                            }
                        }
                    }
                }
            }
        }



        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public Date getCurrentDate(){
        Date toDay =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String toDayStr = sdf.format(toDay);
        Date newDate = null;
        try {
            newDate = sdf.parse(toDayStr);

        }catch (Exception e){
            return newDate;
        }
        return newDate;
    }





}
